<template>
  <div class="dashboard-container">
    <div class="header">
      <h1>用户数据统计看板</h1>
    </div>

    <div class="section">
      <div class="section-title">各地区分布</div>
      <table class="region-table">
        <thead>
        <tr>
          <th>地区</th>
          <th>用户数</th>
          <th>地区</th>
          <th>用户数</th>
          <th>地区</th>
          <th>用户数</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(row, index) in tableData" :key="index">
          <td>{{ row[0].region }}</td>
          <td>{{ row[0].count }}</td>
          <td>{{ row[1].region }}</td>
          <td>{{ row[1].count }}</td>
          <td>{{ row[2].region }}</td>
          <td>{{ row[2].count }}</td>
        </tr>
        </tbody>
      </table>
    </div>

    <div class="section">
      <div class="section-title">各时间段在线用户</div>
      <div class="time-periods">
        <button
            v-for="period in timePeriods"
            :key="period.value"
            class="time-btn"
            :class="{ active: activePeriod === period.value }"
            @click="changePeriod(period.value)"
        >
          {{ period.label }}
        </button>
        <el-date-picker
            v-if="activePeriod === 'custom'"
            v-model="customDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleDateChange"
        />
      </div>

      <div class="user-activity-container">
        <div class="chart-card full-width">
          <div class="chart-title">用户活跃趋势</div>
          <div class="activity-chart" ref="activityChart"></div>
        </div>
      </div>
    </div>

    <div class="charts-container">
      <div class="chart-card">
        <div class="chart-title">性别比例</div>
        <div class="chart-container" ref="genderChart"></div>
      </div>

      <div class="chart-card">
        <div class="chart-title">年龄段分布</div>
        <div class="age-chart-container" ref="ageChart"></div>
      </div>
    </div>

    <div class="footer">
      <p>数据来源：Aware UE 交互设计</p>
      <p>©2023 Aware UE 交互设计，未经许可不得转载。版权所有请勿转载。</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'

// 图表引用
const genderChart = ref(null)
const ageChart = ref(null)
const activityChart = ref(null)
let genderChartInstance = null
let ageChartInstance = null
let activityChartInstance = null

// 数据
const tableData = ref([
  [
    { region: '北京', count: 30000 },
    { region: '河北', count: 30000 },
    { region: '吉林', count: 30000 }
  ],
  [
    { region: '上海', count: 30000 },
    { region: '山西', count: 30000 },
    { region: '黑龙江', count: 30000 }
  ],
  [
    { region: '天津', count: 30000 },
    { region: '辽宁', count: 30000 },
    { region: '江苏', count: 30000 }
  ],
  [
    { region: '浙江', count: 30000 },
    { region: '安徽', count: 30000 },
    { region: '福建', count: 30000 }
  ],
  [
    { region: '江西', count: 30000 },
    { region: '山东', count: 30000 },
    { region: '河南', count: 30000 }
  ],
  [
    { region: '湖北', count: 30000 },
    { region: '湖南', count: 30000 },
    { region: '广东', count: 30000 }
  ],
  [
    { region: '海南', count: 30000 },
    { region: '四川', count: 30000 },
    { region: '贵州', count: 30000 }
  ],
  [
    { region: '云南', count: 30000 },
    { region: '陕西', count: 30000 },
    { region: '甘肃', count: 30000 }
  ],
  [
    { region: '青海', count: 30000 },
    { region: '内蒙古', count: 30000 },
    { region: '广西', count: 30000 }
  ],
  [
    { region: '西藏', count: 30000 },
    { region: '宁夏', count: 30000 },
    { region: '新疆', count: 30000 }
  ]
])

const timePeriods = ref([
  { value: 'yesterday', label: '昨天' },
  { value: 'last7days', label: '最近7天' },
  { value: 'last30days', label: '最近30天' },
  { value: 'custom', label: '自定义日期' }
])

const activePeriod = ref('yesterday')
const customDateRange = ref([])

const genderData = [
  { value: 71.55, name: '男' },
  { value: 29.45, name: '女' }
]

const ageData = [
  { name: '0-18岁', value: 8 },
  { name: '18-23岁', value: 28 },
  { name: '24-30岁', value: 24 },
  { name: '31-40岁', value: 22 },
  { name: '41-50岁', value: 12 },
  { name: '50岁以上', value: 6 }
]

// 方法
const changePeriod = (period) => {
  activePeriod.value = period
  initActivityChart()
}

const handleDateChange = () => {
  if (customDateRange.value && customDateRange.value.length === 2) {
    initActivityChart()
  }
}

const initActivityChart = () => {
  if (!activityChart.value) return

  if (activityChartInstance) {
    activityChartInstance.dispose()
  }

  activityChartInstance = echarts.init(activityChart.value)

  // 生成模拟数据
  const hours = Array.from({ length: 25 }, (_, i) => i)
  const data = hours.map(hour => {
    // 模拟用户活跃数据，高峰在16-17点和20-21点
    let value = 500 + Math.random() * 500
    if (hour >= 16 && hour <= 17) {
      value = 2000 + Math.random() * 1000
    } else if (hour >= 20 && hour <= 21) {
      value = 2500 + Math.random() * 500
    } else if (hour >= 2 && hour <= 6) {
      value = 100 + Math.random() * 200
    } else if (hour >= 10 && hour <= 12) {
      value = 1000 + Math.random() * 500
    }
    return Math.round(value)
  })

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        return `时间: ${params[0].axisValue}:00<br/>用户数: ${params[0].data}`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: hours,
      axisLabel: {
        formatter: function(value) {
          return value
        }
      },
      axisLine: {
        lineStyle: {
          color: '#ccc'
        }
      }
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 3000,
      interval: 500,
      axisLabel: {
        formatter: '{value}'
      },
      axisLine: {
        lineStyle: {
          color: '#ccc'
        }
      },
      splitLine: {
        lineStyle: {
          color: '#f0f0f0',
          type: 'dashed'
        }
      }
    },
    series: [
      {
        name: '在线用户数',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: {
          width: 3,
          color: '#5470c6'
        },
        itemStyle: {
          color: '#5470c6',
          borderWidth: 2,
          borderColor: '#fff'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0, color: 'rgba(84, 112, 198, 0.5)'
            }, {
              offset: 1, color: 'rgba(84, 112, 198, 0.1)'
            }]
          }
        },
        markPoint: {
          data: [
            { type: 'max', name: '最大值' },
            { coord: [16, data[16]], name: '高峰时段' },
            { coord: [20, data[20]], name: '高峰时段' }
          ],
          symbol: 'pin',
          symbolSize: 50,
          itemStyle: {
            color: '#ee6666'
          }
        },
        data: data
      }
    ]
  }

  activityChartInstance.setOption(option)
}

const initGenderChart = () => {
  if (!genderChart.value) return

  genderChartInstance = echarts.init(genderChart.value)

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}%'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'center',
      data: ['男', '女']
    },
    series: [
      {
        name: '性别比例',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: genderData
      }
    ],
    color: ['#5470c6', '#91cc75']
  }

  genderChartInstance.setOption(option)
}

const initAgeChart = () => {
  if (!ageChart.value) return

  ageChartInstance = echarts.init(ageChart.value)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value}%'
      }
    },
    yAxis: {
      type: 'category',
      data: ageData.map(item => item.name).reverse()
    },
    series: [
      {
        name: '用户占比',
        type: 'bar',
        data: ageData.map(item => item.value).reverse(),
        itemStyle: {
          color: function(params) {
            const colorList = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272']
            return colorList[params.dataIndex % colorList.length]
          }
        },
        label: {
          show: true,
          position: 'right',
          formatter: '{c}%'
        }
      }
    ]
  }

  ageChartInstance.setOption(option)
}

const handleResize = () => {
  if (genderChartInstance) {
    genderChartInstance.resize()
  }
  if (ageChartInstance) {
    ageChartInstance.resize()
  }
  if (activityChartInstance) {
    activityChartInstance.resize()
  }
}

// 生命周期
onMounted(() => {
  initGenderChart()
  initAgeChart()
  initActivityChart()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (genderChartInstance) {
    genderChartInstance.dispose()
  }
  if (ageChartInstance) {
    ageChartInstance.dispose()
  }
  if (activityChartInstance) {
    activityChartInstance.dispose()
  }
})
</script>

<style scoped>
.dashboard-container {
  max-width: 1200px;
  margin: 0 auto;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 24px;
}

.header {
  text-align: center;
  margin-bottom: 24px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 16px;
}

.header h1 {
  color: #303133;
  font-size: 24px;
  font-weight: 500;
}

.section {
  margin-bottom: 32px;
}

.section-title {
  font-size: 18px;
  color: #303133;
  margin-bottom: 16px;
  font-weight: 500;
  display: flex;
  align-items: center;
}

.section-title::before {
  content: "";
  display: inline-block;
  width: 4px;
  height: 16px;
  background-color: #409eff;
  margin-right: 8px;
  border-radius: 2px;
}

.region-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 16px;
}

.region-table th,
.region-table td {
  border: 1px solid #ebeef5;
  padding: 12px 16px;
  text-align: center;
}

.region-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
}

.time-periods {
  display: flex;
  gap: 12px;
  margin-bottom: 24px;
  align-items: center;
  flex-wrap: wrap;
}

.time-btn {
  padding: 8px 16px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background: white;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s;
}

.time-btn.active {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.user-activity-container {
  display: block;
  margin-bottom: 32px;
}

.chart-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 16px;
}

.chart-card.full-width {
  width: 100%;
}

.chart-title {
  font-size: 16px;
  color: #303133;
  margin-bottom: 16px;
  text-align: center;
  font-weight: 500;
}

.activity-chart {
  width: 100%;
  height: 400px;
}

.charts-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
}

.chart-container {
  width: 100%;
  height: 340px;
}

.age-chart-container {
  width: 100%;
  height: 340px;
}

.footer {
  text-align: center;
  margin-top: 32px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
  color: #909399;
  font-size: 14px;
}

@media (max-width: 768px) {
  .charts-container {
    grid-template-columns: 1fr;
  }

  .region-table {
    font-size: 14px;
  }

  .region-table th,
  .region-table td {
    padding: 8px 10px;
  }
}
</style>